<template>
  <div class="header">
    <div class="left">
      <div><el-icon class="back" v-if="true" @click="logout()">
          <UserFilled />
        </el-icon>
      </div>
      <span style="font-size: 16px">{{ state.name }}</span>

    </div>
    <div class="right">
      <el-popover placement="bottom" :width="320" trigger="click" popper-class="popper-user-box">
        <template #reference>
          <div class="author">
            <i class="icon el-icon-s-custom" />
            <!-- {{ state.userInfo && state.userInfo.nickName || '' }} -->
            <i class="el-icon-caret-bottom" />
          </div>
        </template>
        <div class="nickname">
          <p>登录名：</p>
          <!-- {{ state.userInfo && state.userInfo.loginUserName || '' }} -->
          <p>昵称：</p>
          <!-- {{ state.userInfo && state.userInfo.nickName || '' }} -->
          <el-tag size="small" effect="dark" class="logout" @click="logout">退出</el-tag>
        </div>
      </el-popover>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
//import router from '../router'
import { useStore } from 'vuex'
import { postRequest } from '../api/axiosRequest';

const router = useRouter()
const state = reactive({
  name: '请登录',
  userInfo: null, // 用户信息变量
  hasBack: false, // 是否展示返回icon
})



const logout = async () => {
  console.log('clear');
  const result = await postRequest("/user/logout");
  console.log(result);
  console.log("result.status:" + result.status);
  console.log("result.data.status:" + result.data.status);
  if (result.status === 200) {
    if (result.data.status === 1) {
      router.push('/login')
    } else if (result.data.status === 1) {
      router.push('/login')
    }
  }
  localStorage.clear();
  ElNotification({
    title: '退出提示',
    message: result.data.msg,
    type: 'success'
  })
}

// // 检查token有效性的方法
const checkToken = () => {
  // 获取token过期时间，并且它转换为日期对象
  const storedExpirationTime = new Date(localStorage.getItem('expirationTime') || '');
  console.log("storedExpirationTime:" + storedExpirationTime);

  // 获取当前时间
  // 前端获取到的当前时间
  const currentTime = new Date();
  // 将当前时间转换为 UTC 字符串
  const currentTimeUTC = currentTime.toUTCString();
  // 解析 UTC 字符串
  const currentTimeObject = new Date(currentTimeUTC);
  console.log("new Date():" + currentTimeObject)

  if (storedExpirationTime < currentTimeObject) {
    console.log("new Date():" + new Date());
    // token已经过期，提示用户重新登录
    localStorage.clear()
  }
};

const store = useStore();
// 初始化执行方法
onMounted(() => {
  // 检查token是否有效
  checkToken();

  let userRole = localStorage.getItem('role');
  let userId = localStorage.getItem('userId');
  console.log("userId:", userId);
  if (userId) {
    store.commit('SetUserId', userId)
    console.log(222);
  }




  // // 获取存储在 store 中的 userId
  const userIds = computed(() => store.state.userId);

  console.log("Current User ID in another component:", userIds.value);

  if (!(router.currentRoute.value.fullPath.includes('login') || router.currentRoute.value.fullPath.includes('signup'))) {
    if (userRole === '0' && router.currentRoute.value.fullPath.includes('traveler')) {
      state.name = '欢迎您，游客，点此退出登录';
    } else if (userRole === '1' && router.currentRoute.value.fullPath.includes('manager')) {
      console.log(111);
      state.name = '欢迎您，管理员，点此退出登录';
    } else if (userRole === '2' && router.currentRoute.value.fullPath.includes('hotelmanager')) {
      state.name = '欢迎您，酒店管理员，点此退出登录';
    } else {
      alert('账号权限错误!');
      console.log(router.currentRoute.value.fullPath.includes('manager'));
      localStorage.clear();
      router.push('/login');
    }
  }
})
// // 获取用户信息
// const getUserInfo = async () => {
//   // const userInfo = await axios.get('/adminUser/profile')
//   state.userInfo = userInfo
// }
// // 退出登录
// const logout = () => {
//   axios.delete('/logout').then(() => {
//     // 退出之后，将本地保存的 token  清理掉
//     localRemove('token')
//     // 回到登录页
//     router.push({ path: '/login' })
//   })
// }

// router.afterEach((to) => {
//   const { id } = to.query
//   state.name = pathMap[to.name]
//   // level2 和 level3 需要展示返回icon
//   console.log('to.name', to.name)
//   state.hasBack = ['level2', 'level3'].includes(to.name)
// })

// 返回方法
const back = () => {
  router.back()
}
</script>

<style scoped>
.header {
  height: 50px;
  border-bottom: 1px solid #e9e9e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header .left .back {
  border: 1px solid #e9e9e9;
  padding: 5px;
  border-radius: 50%;
  margin-right: 5px;
  cursor: pointer;
}

.right>div>.icon {
  font-size: 18px;
  margin-right: 6px;
}

.author {
  margin-left: 10px;
  cursor: pointer;
}
</style>

<style>
.popper-user-box {
  background: url('https://s.yezgea02.com/lingling-h5/static/account-banner-bg.png') 50% 50% no-repeat !important;
  background-size: cover !important;
  border-radius: 0 !important;
}

.popper-user-box .nickname {
  position: relative;
  color: #ffffff;
}

.popper-user-box .nickname .logout {
  position: absolute;
  right: 0;
  top: 0;
  cursor: pointer;
}
</style>